<?php
session_start();

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '123456');
define('DB_NAME', 'db');

// 确保用户已登录
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

$user_id = $_SESSION['user_id'];
$content = $_POST['content'];

// 检查图片上传状态
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $image = $_FILES['image']['name'];
    $image_temp = $_FILES['image']['tmp_name'];
    // 确保是图片且大小合适
    $check = getimagesize($image_temp);
    if ($check !== false && $check[2] !== FALSE) { // 确认是图片
        // 移动上传的文件
        move_uploaded_file($image_temp, "uploads/$image");
    } else {
        echo "仅支持图片上传且不超过指定大小。";
        exit();
    }
} else {
    echo "图片上传出错: " . $_FILES['image']['error'];
    exit();
}

// 插入动态
$sql = "INSERT INTO posts (content, image, user_id) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssi", $content, $image, $user_id);

if ($stmt->execute()) {
    echo "动态发布成功！";
} else {
    echo "发布失败: " . $stmt->error;
}

$stmt->close();
$conn->close();

header("Location: profile.php");
exit();
?>